﻿using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace TK
{
    public partial class CustomSerializer {        

        void writeComplex(CustomSerializerState state, object value) {            
            var objID = state.writeHeader();

            Int16 processedItems = 0;
            var propInfos = getTypeProps(value.GetType(), false);

            foreach (var item in propInfos)
            {
                if (!state.validToProcessing(item.Value)) continue;
                var v = item.Value.GetValue(value);
                if (v == null) continue;

                var header = state.writeHeader();
                state.writeName(item.Value.StoreName);
                if (writeValue(state, v, item.Key)) processedItems++;
                state.updateHeader(header);
            }

            state.updateHeader(objID, (UInt16) processedItems);
        }

        object readComplex(CustomSerializerState state, Type type)
        {
            var header = state.readHeader();
            var typeName = type.Name;
            var obj = createObject(type);
            var propInfos = getTypeProps(type, true);
            
            //var unknownValues = new Dictionary<string, object>();
            for (var i = 0; i < header.Count; i++)
            {
                var propHeader = state.readHeader();
                var name = state.readName();

                PropInfo propInfo;
                if (propInfos.TryGetValue(name, out propInfo) && state.validToProcessing(propInfo))
                {
                    bool success = false;
                    var value = readValue(state, propInfo.CustomType, type, propInfo.Name, out success);
                    if (!success) state.skipObject(propHeader);
                    else propInfo.SetValue(obj, value);
                }
                else state.skipObject(propHeader);
            }
            return obj;
        }

        //object readUnknown(CustomSerializerState state)
        //{
        //    var typeName = state.readTypeName();
        //    if (string.IsNullOrEmpty(typeName)) return null;

        //    var storeType = getTypeByName(typeName, settings.ClassMap);
        //    if (storeType == null)
        //    {




        //    }
        //    else
        //    {
        //        TypeHandler handler;
        //        if (SimpleTypes.TryGetValue(storeType, out handler)) return handler.Read(state);
        //    }
        //    return null;
        //}
    }
}